关于类中定义操作符>>问题

来源:百度知道 编辑:UC知道 时间:2024/05/30 16:06:50
假设 a.txt 中有数3 4;
目标是定义操作符>>
将3,4传给x,y

#include <iostream>
#include <fstream>
using namespace std;

class Point
{
public:
Point(const int &m=0,const int &n=0):x(m),y(n){}
void display();
friend ifstream& operator <<(ifstream&,Point&);
private:
int x,y;
};

void Point::display()
{
cout << x << " \t" << y;
}

ifstream& operator <<(ifstream& in,Point &t)
{
in >> t.x >> t.y;
return in;
}

int main()
{
ifstream in("a.txt");
Point temp;
in >> temp;
temp.display();
system ("pause");
return 0;
}

问题出在哪里? 怎样才能正确定义?

我还想问下能不能重载操作符

ostream operator <<(.......)

ofstream 里面的操作符,你是不能重载的,除非你是要继承这个类,且如果ofstream 里面的这个<<操作符是虚函数,你才能重载覆盖这个函数。
所以你的这段
ifstream& operator <<(ifstream& in,Point &t)
{
in >> t.x >> t.y;
return in;
}
是错误的
//////////正确的程序如下
#include <iostream>
#include <fstream>
using namespace std;

class Point
{
public:
Point(const int &m=0,const int &n=0):x(m),y(n){}
void display();
void operator <<(ifstream &in){in >> x >> y; }
private:
int x,y;
};

void Point::display()
{
cout << x << " \t" << y;
}

int main()
{
ifstream in("a.txt");
Point temp;
temp<<in;
temp.display();
system ("pause");
return 0;
}
windowsXP&vc6.0下调试通过,a.txt中的文件内容用空格区分开,才能正确读入